import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useRoleStore } from '@/stores/role'
import { useUserStore } from '@/stores/user'
import { useBreadcrumbStore } from '@/stores/breadcrumb.ts'
import type { BreadcrumbItem } from '@/types/router'
import { getDynamicTitle } from '@/utils/route.ts'
import { ElLoading } from 'element-plus'

const routes: RouteRecordRaw[] = [
    // 无面包屑的页面
    {
        path: '/',
        component: () => import('@/layout/Login.vue'),
        meta: {
            requiresAuth: false,
        },
        children: [
            {
                path: '',
                name: 'login',
                component: () => import('@/views/Login.vue'),
                meta: {
                    requiresAuth: false,
                },
            },
            {
                path: 'forgetPwd',
                name: 'forgetPwd',
                component: () => import('@/views/ForgetPwd.vue'),
                meta: {
                    requiresAuth: false,
                },
            },
            {
                path: 'forgetPwd/continue',
                name: 'forgetPwdContinue',
                component: () => import('@/views/ForgetPwd_continue.vue'),
                meta: {
                    requiresAuth: false,
                },
            },
            {
                path: 'resetPassword',
                name: 'resetPassword',
                component: () => import('@/views/ResetPassword.vue'),
                meta: {
                    requiresAuth: false,
                },
            },
        ],
    },
    {
        path: '/console',
        component: () => import('@/layout/PageBox.vue'),
        meta: {
            requiresAuth: true,
            breadcrumb: [{ titleKey: 'router_tit.home', to: '/console' }],
        },
        children: [
            // 首页
            {
                path: '',
                name: 'home',
                component: () => import('@/views/Home.vue'),
                meta: {
                    requiresAuth: true,
                    hideBanner: true,
                    hideBreadcrumb: true,
                    hideNavigation: true,
                },
            },

            // 用户模块
            {
                path: 'user',
                meta: {
                    requiresAuth: true,
                    breadcrumb: [{ titleKey: 'router_tit.user', to: '/console/user/profile' }],
                },
                children: [
                    {
                        path: 'manager',
                        name: 'userManager',
                        component: () => import('@/views/user/manager/index.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.userManager' }],
                        },
                    },
                    {
                        path: ':userId',
                        name: 'user',
                        component: () => import('@/views/user/index.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.user', dynamic: true, keyName: 'userId' }],
                        },
                    },
                    {
                        path: 'profile',
                        name: 'userProfile',
                        component: () => import('@/views/user/Profile.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.userProfile' }],
                        },
                    },
                    {
                        path: 'edit',
                        name: 'userEdit',
                        component: () => import('@/views/user/Edit.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.userEdit' }],
                        },
                    },
                    {
                        path: 'create',
                        name: 'userCreate',
                        component: () => import('@/views/user/Create.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.userCreate' }],
                        },
                    },
                    {
                        path: 'changePwd',
                        name: 'userChangePwd',
                        component: () => import('@/views/user/ChangePwd.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.userChangePwd' }],
                        },
                    },
                    {
                        path: 'preferences',
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.userPreferences', to: '/console/user/preferences' }],
                        },
                        children: [
                            {
                                path: '',
                                name: 'userPreferences',
                                component: () => import('@/views/user/preferences/index.vue'),
                            },
                            {
                                path: 'language',
                                name: 'userPreferencesLanguage',
                                component: () => import('@/views/user/preferences/Language.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.userPreferencesLanguage' }],
                                },
                            },
                            {
                                path: 'forum',
                                name: 'userPreferencesForum',
                                component: () => import('@/views/user/preferences/Forum.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.userPreferencesForum' }],
                                },
                            },
                            {
                                path: 'editor',
                                name: 'userPreferencesEditor',
                                component: () => import('@/views/user/preferences/Editor.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.userPreferencesEditor' }],
                                },
                            },
                            {
                                path: 'calendar',
                                name: 'userPreferencesCalendar',
                                component: () => import('@/views/user/preferences/Calendar.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.userPreferencesCalendar' }],
                                },
                            },
                            {
                                path: 'contentbank',
                                name: 'userPreferencesContentbank',
                                component: () => import('@/views/user/preferences/Contentbank.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.userPreferencesContentbank' }],
                                },
                            },
                            {
                                path: 'notification',
                                name: 'userPreferencesNotification',
                                component: () => import('@/views/message/NotificationPreferences.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.userPreferencesNotification' }],
                                },
                            },
                        ],
                    },
                ],
            },

            // 仪表盘
            {
                path: 'my',
                name: 'my',
                component: () => import('@/views/my/index.vue'),
                meta: {
                    requiresAuth: true,
                    hideNavigation: true,
                    breadcrumb: [{ titleKey: 'router_tit.my' }],
                },
            },

            // 消息模块
            {
                path: 'message',
                meta: {
                    requiresAuth: true,
                    breadcrumb: [{ titleKey: 'router_tit.notification', to: '/console/message' }],
                },
                children: [
                    {
                        path: '',
                        name: 'message',
                        component: () => import('@/views/message/index.vue'),
                        meta: {
                            requiresAuth: true,
                            hideHeader: false,
                            hideFooter: false,
                            hideBanner: false,
                        },
                    },
                    {
                        path: 'messageList',
                        name: 'messageList',
                        component: () => import('@/views/message/messageList.vue'),
                        meta: {
                            requiresAuth: true,
                            hideHeader: false,
                            hideFooter: false,
                            hideBanner: false,
                        },
                    },
                    {
                        path: 'notifications',
                        name: 'messageNotifications',
                        component: () => import('@/views/message/Notifications.vue'),
                        meta: {
                            requiresAuth: true,
                            hideHeader: false,
                            hideFooter: false,
                            breadcrumb: [{ titleKey: 'router_tit.messageNotifications' }],
                        },
                    },
                ],
            },

            // 标签搜索
            {
                path: 'tag/search',
                name: 'tagSearch',
                component: () => import('@/views/tag/Search.vue'),
                meta: {
                    requiresAuth: true,
                    breadcrumb: [{ titleKey: 'router_tit.tagSearch' }],
                },
            },

            // 日历
            {
                path: 'calendar/view',
                name: 'calendar',
                component: () => import('@/views/calendar/View.vue'),
                meta: {
                    requiresAuth: true,
                    breadcrumb: [{ titleKey: 'router_tit.calendar' }],
                },
            },

            // 网站管理模块
            {
                path: 'mod',
                meta: {
                    requiresAuth: true,
                    breadcrumb: [{ titleKey: 'router_tit.mod' }],
                },
                children: [
                    // 公告管理
                    {
                        path: 'announcement',
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.modAnnouncement', to: '/console/mod/announcement' }],
                        },
                        children: [
                            {
                                path: '',
                                name: 'modAnnouncement',
                                component: () => import('@/views/mod/Announcement/index.vue'),
                            },
                            {
                                path: 'discuss/:announcementDiscussId',
                                name: 'modAnnouncementDiscuss',
                                component: () => import('@/views/mod/Announcement/Discuss.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.modAnnouncementDiscuss', dynamic: true, keyName: 'announcementDiscussId' }],
                                },
                            },
                        ],
                    },

                    // 常見問題
                    {
                        path: 'book',
                        name: 'modBook',
                        component: () => import('@/views/mod/Book/index.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.modBook' }],
                        },
                    },

                    // 联系管理
                    {
                        path: 'contact',
                        name: 'modContact',
                        component: () => import('@/views/mod/Contact/index.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.modContact' }],
                        },
                    },
                ],
            },

            // 课程模块
            {
                path: 'course',
                meta: {
                    requiresAuth: true,
                    breadcrumb: [{ titleKey: 'router_tit.course' }],
                },
                children: [
                    // 课程基础路由
                    {
                        path: ':courseId(\\d+)',
                        name: 'course',
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.course', dynamic: true, keyName: 'courseId', to: '/console/course/:courseId' }],
                        },
                        children: [
                            // 论坛管理
                            {
                                path: 'forum',
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.forum', to: '/console/course/:courseId/forum/view/' }],
                                },
                                children: [
                                    {
                                        path: 'view',
                                        name: 'modForum',
                                        component: () => import('@/views/mod/Forum/index.vue'),
                                        meta: {
                                            requiresAuth: true,
                                            breadcrumb: [{ titleKey: 'router_tit.modForum', dynamic: true }],
                                        },
                                    },

                                    {
                                        path: '',
                                        name: 'modForum2',
                                        component: () => import('@/views/mod/Forum/index.vue'),
                                        meta: {
                                            requiresAuth: true,
                                            breadcrumb: [{ titleKey: 'router_tit.modForum2', dynamic: true }],
                                        },
                                    },

                                    {
                                        path: 'discuss',
                                        name: 'modForumDiscuss',
                                        component: () => import('@/views/mod/Forum/Discuss.vue'),
                                        meta: {
                                            requiresAuth: true,
                                            // breadcrumb: [{ titleKey: 'router_tit.modForumDiscuss', dynamic: true }],
                                            breadcrumb: [{ titleKey: 'router_tit.modForumDiscuss', dynamic: true }],
                                        },
                                    },
                                    // {
                                    //     path: 'discuss2',
                                    //     name: 'modForumDiscuss2',
                                    //     component: () => import('@/views/mod/Forum/Discuss.vue'),
                                    //     meta: {
                                    //         requiresAuth: true,
                                    //         // breadcrumb: [{ titleKey: 'router_tit.modForumDiscuss', dynamic: true }],
                                    //         breadcrumb: [{ titleKey: 'router_tit.modForumDiscuss', dynamic: true }],
                                    //     },
                                    // },
                                    // {
                                    //     path: 'search',
                                    //     name: 'modForumSearch',
                                    //     component: () => import('@/views/mod/Forum/Search.vue'),
                                    //     meta: {
                                    //         requiresAuth: true,
                                    //         breadcrumb: [{ titleKey: 'router_tit.modForumSearch' }],
                                    //     },
                                    // },
                                ],
                            },

                            {
                                path: '',
                                name: 'courseNull',
                                component: () => import('@/views/course/index.vue'),
                                meta: {
                                    requiresAuth: true,
                                },
                            },
                            // 课程编辑
                            {
                                path: 'edit',
                                name: 'courseEdit',
                                component: () => import('@/views/course/Edit.vue'),
                                meta: {
                                    requiresAuth: true,
                                    hideNavigation: true,
                                    breadcrumb: [{ titleKey: 'router_tit.courseEdit' }],
                                },
                            },
                            // 课程资源
                            {
                                path: 'resource/edit',
                                name: 'courseResourceEdit',
                                component: () => import('@/views/course/ResourceEdit.vue'),
                                meta: {
                                    requiresAuth: true,
                                    hideNavigation: true,
                                    breadcrumb: [{ titleKey: 'router_tit.courseResourceEdit' }],
                                },
                            },
                            // 课程单元
                            {
                                path: 'unit',
                                children: [
                                    {
                                        path: ':unitId',
                                        name: 'unit',
                                        meta: {
                                            requiresAuth: true,
                                            breadcrumb: [{ titleKey: 'router_tit.unit', dynamic: true, keyName: 'unitId', to: '/console/course/:courseId/unit/:unitId' }],
                                        },
                                        children: [
                                            {
                                                path: '',
                                                name: 'unitNull',
                                                component: () => import('@/views/course/View.vue'),
                                            },
                                            // 单元编辑
                                            {
                                                path: 'edit',
                                                name: 'unitEdit',
                                                component: () => import('@/views/course/UnitEdit.vue'),
                                                meta: {
                                                    requiresAuth: true,
                                                    hideNavigation: true,
                                                    breadcrumb: [{ titleKey: 'router_tit.unitEdit' }],
                                                },
                                            },
                                            // 单元下的各种资源
                                            {
                                                path: 'videoTime/:videoId',
                                                name: 'videoTime',
                                                component: () => import('@/views/mod/VideoTime/index.vue'),
                                                meta: {
                                                    requiresAuth: true,
                                                    breadcrumb: [{ titleKey: 'router_tit.videoTime', dynamic: true, keyName: 'videoId' }],
                                                },
                                            },
                                            {
                                                path: 'quiz',
                                                children: [
                                                    {
                                                        path: ':quizId',
                                                        name: 'quiz',
                                                        meta: {
                                                            requiresAuth: true,
                                                            breadcrumb: [{ titleKey: 'router_tit.quiz', dynamic: true, keyName: 'quizId', to: '/console/course/:courseId/unit/:unitId/quiz/:quizId' }],
                                                        },
                                                        children: [
                                                            {
                                                                path: '',
                                                                name: 'quizNull',
                                                                component: () => import('@/views/mod/Quiz/View.vue'),
                                                            },
                                                            {
                                                                path: 'attempt',
                                                                name: 'quizAttempt',
                                                                component: () => import('@/views/mod/Quiz/Attempt.vue'),
                                                                meta: {
                                                                    requiresAuth: true,
                                                                    hideNavigation: true,
                                                                    breadcrumb: [{ titleKey: 'router_tit.quizAttempt' }],
                                                                },
                                                            },
                                                            {
                                                                path: 'review/:recordId',
                                                                name: 'quizReview',
                                                                component: () => import('@/views/mod/Quiz/Review.vue'),
                                                                meta: {
                                                                    requiresAuth: true,
                                                                    hideNavigation: true,
                                                                    breadcrumb: [{ titleKey: 'router_tit.quizReview' }],
                                                                },
                                                            },
                                                            {
                                                                path: 'summary/:recordId',
                                                                name: 'quizSummary',
                                                                component: () => import('@/views/mod/Quiz/Summary.vue'),
                                                                meta: {
                                                                    requiresAuth: true,
                                                                    hideNavigation: true,
                                                                    breadcrumb: [{ titleKey: 'router_tit.quizSummary' }],
                                                                },
                                                            },
                                                            {
                                                                path: 'report',
                                                                name: 'quizReport',
                                                                component: () => import('@/views/mod/Quiz/Report.vue'),
                                                                meta: {
                                                                    requiresAuth: true,
                                                                    breadcrumb: [{ titleKey: 'router_tit.quizReport' }],
                                                                },
                                                            },
                                                        ],
                                                    },
                                                ],
                                            },
                                            {
                                                path: 'folder/:folderId',
                                                name: 'folder',
                                                component: () => import('@/views/mod/Folder/View.vue'),
                                                meta: {
                                                    requiresAuth: true,
                                                    breadcrumb: [{ titleKey: 'router_tit.folder', dynamic: true, keyName: 'folderId' }],
                                                },
                                            },
                                            {
                                                path: 'assign',
                                                children: [
                                                    {
                                                        path: ':assignId',
                                                        name: 'assign',
                                                        meta: {
                                                            requiresAuth: true,
                                                            breadcrumb: [
                                                                {
                                                                    titleKey: 'router_tit.assign',
                                                                    dynamic: true,
                                                                    keyName: 'assignId',
                                                                    to: '/console/course/:courseId/unit/:unitId/assign/:assignId',
                                                                },
                                                            ],
                                                        },
                                                        children: [
                                                            {
                                                                path: '',
                                                                name: 'assignNull',
                                                                component: () => import('@/views/mod/Assign/View.vue'),
                                                            },
                                                            {
                                                                path: 'report',
                                                                name: 'assignReport',
                                                                component: () => import('@/views/mod/Assign/Report.vue'),
                                                                meta: {
                                                                    requiresAuth: true,
                                                                    breadcrumb: [{ titleKey: 'router_tit.assignReport' }],
                                                                },
                                                            },
                                                            {
                                                                path: 'correct',
                                                                name: 'assignCorrect',
                                                                component: () => import('@/views/mod/Assign/Correct.vue'),
                                                                meta: {
                                                                    requiresAuth: true,
                                                                    hideHeader: true,
                                                                    hideFooter: true,
                                                                    hideNavigation: true,
                                                                    hideBanner: true,
                                                                    hideBreadcrumb: true,
                                                                    breadcrumb: [{ titleKey: 'router_tit.assignCorrect' }],
                                                                },
                                                            },
                                                        ],
                                                    },
                                                ],
                                            },
                                        ],
                                    },
                                    // 创建单元
                                    {
                                        path: 'create',
                                        name: 'unitCreate',
                                        component: () => import('@/views/course/UnitEdit.vue'),
                                        meta: {
                                            requiresAuth: true,
                                            hideNavigation: true,
                                            breadcrumb: [{ titleKey: 'router_tit.unitCreate' }],
                                        },
                                    },
                                ],
                            },
                            // 成绩
                            {
                                path: 'grade',
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.grade' }],
                                },
                                children: [
                                    {
                                        path: '',
                                        name: 'grade',
                                        component: () => import('../views/grade/Report/Overview/index.vue'),
                                    },
                                    {
                                        path: 'user',
                                        name: 'gradeUser',
                                        component: () => import('../views/grade/Report/User/index.vue'),
                                        meta: {
                                            requiresAuth: true,
                                            breadcrumb: [{ titleKey: 'router_tit.gradeUser' }],
                                        },
                                    },
                                    {
                                        path: 'rater',
                                        name: 'gradeRater',
                                        component: () => import('../views/grade/Report/Grader/index.vue'),
                                        meta: {
                                            requiresAuth: true,
                                            deniedRoleIds: [3],
                                            breadcrumb: [{ titleKey: 'router_tit.gradeRater' }],
                                        },
                                    },
                                ],
                            },
                            // 成员
                            {
                                path: 'member',
                                name: 'courseMember',
                                component: () => import('@/views/course/member/index.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.courseMember' }],
                                },
                            },
                        ],
                    },
                    // 创建课程
                    {
                        path: 'create',
                        name: 'courseCreate',
                        component: () => import('@/views/course/Edit.vue'),
                        meta: {
                            requiresAuth: true,
                            hideNavigation: true,
                            breadcrumb: [{ titleKey: 'router_tit.courseCreate' }],
                        },
                    },
                    // 课程分类等其他全局路由
                    {
                        path: 'category',
                        name: 'courseCategory',
                        meta: {
                            requiresAuth: true,
                            hideNavigation: true,
                            breadcrumb: [{ titleKey: 'router_tit.courseCategory', to: '/console/course/category' }],
                        },
                        children: [
                            {
                                path: '',
                                name: 'courseCategoryNull',
                                component: () => import('@/views/course/category/index.vue'),
                            },
                            {
                                path: 'edit/:id',
                                name: 'courseCategoryEdit',
                                component: () => import('@/views/course/category/Edit.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.courseCategoryEdit' }],
                                },
                            },
                            {
                                path: 'create',
                                name: 'courseCategoryCreate',
                                component: () => import('@/views/course/category/Edit.vue'),
                                meta: {
                                    requiresAuth: true,
                                    breadcrumb: [{ titleKey: 'router_tit.courseCategoryCreate' }],
                                },
                            },
                        ],
                    },
                    // 所有课程的成绩
                    {
                        path: 'grades',
                        name: 'grades',
                        component: () => import('../views/grade/Report/Overview/index.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.grades' }],
                        },
                    },
                ],
            },

            // 题库模块
            {
                path: 'question',
                name: 'question',
                meta: {
                    requiresAuth: true,
                    hideNavigation: true,
                    breadcrumb: [{ titleKey: 'router_tit.question', to: '/console/question' }],
                },
                children: [
                    {
                        path: '',
                        name: 'questionNull',
                        component: () => import('@/views/question/index.vue'),
                    },
                    {
                        path: 'edit/:id',
                        name: 'questionEdit',
                        component: () => import('@/views/question/Edit.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.questionEdit' }],
                        },
                    },
                    {
                        path: 'create',
                        name: 'questionCreate',
                        component: () => import('@/views/question/Edit.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.questionCreate' }],
                        },
                    },
                    {
                        path: 'category',
                        name: 'questionCategory',
                        component: () => import('@/views/question/Category.vue'),
                        meta: {
                            requiresAuth: true,
                            breadcrumb: [{ titleKey: 'router_tit.questionCategory' }],
                        },
                    },
                ],
            },

            // 授权成功 页面
            {
                path: 'authSuccess',
                name: 'authSuccess',
                component: () => import('@/views/AuthSuccess.vue'),
                meta: {
                    requiresAuth: true,
                    hideNavigation: true,
                    hideBreadcrumb: true,
                },
            },
        ],
    },
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL), // 保持这个配置
    routes,
})

router.beforeEach(async (to, from, next) => {
    ElLoading.service({
        lock: true,
        text: '页面加载中...',
        background: 'rgba(250, 250, 250, 0.3)',
    })

    const authStore = useAuthStore()
    const roleStore = useRoleStore()
    const breadcrumbStore = useBreadcrumbStore()
    const userStore = useUserStore()

    if (!to.meta.requiresAuth) return next()
    if (!authStore.isAuthenticated) return next('/')

    if (to.meta.deniedRoleIds) {
        if (roleStore.isSuperAdmin) return next()
        if (roleStore.currentRole && to.meta.deniedRoleIds.includes(roleStore.currentRole.id)) return next('/unauthorized')
    }

    if (!userStore.userinfoL) await userStore.getUserInfoL()

    // S 面包屑配置
    // 收集所有匹配路由的面包屑配置
    const breadcrumbs = to.matched.reduce((acc, record) => {
        if (record.meta.breadcrumb) {
            const items = record.meta.breadcrumb
            return [...acc, ...items]
        }
        return acc
    }, [] as BreadcrumbItem[])

    // 处理动态标题
    const processedBreadcrumbs: BreadcrumbItem[] = []
    for (const item of breadcrumbs) {
        if (item.dynamic && item.keyName) {
            const title = await getDynamicTitle(to.params, item.keyName)
            processedBreadcrumbs.push({
                ...item,
                title,
            })
        } else {
            processedBreadcrumbs.push(item)
        }
    }

    breadcrumbStore.setBreadcrumbs(processedBreadcrumbs)
    // E 面包屑配置

    next()
})

// 在路由后置钩子中关闭加载效果
router.afterEach(() => {
    // 关闭加载效果
    setTimeout(() => {
        ElLoading.service().close()
    }, 1000)
})

export default router
